package db

import (
	"gitee.com/Hu-Lyndon/distill-resk/infra"
	_ "github.com/go-sql-driver/mysql"
	"github.com/go-xorm/xorm"
	"github.com/kataras/golog"
	log "github.com/sirupsen/logrus"
	"github.com/tietang/props/kvs"
)

var (
	engineGroup  *xorm.EngineGroup
)

func EngineGroup()  *xorm.EngineGroup {
	return engineGroup
}


// xorm数据库starter，并且设置为全局
type XormDatabaseStarter struct {
	infra.BaseStarter
}

// 数据库的实例化启动生命周期晚于配置文件加载，所以放到Setup中
func (s *XormDatabaseStarter) Setup(ctx infra.StarterContext) {
	var (
		err error
	)

	conf := ctx.Props()

	dbMaster := DBConfigInfo{}
	err = kvs.Unmarshal(conf, &dbMaster, "db.master")

	dbSlave := DBConfigInfo{}
	err = kvs.Unmarshal(conf, &dbSlave, "db.slave")

	dbEngines := DBEngines{
		DbMasterConfigInfo: &dbMaster,
		DbSlaveConfigInfo:  &dbSlave,
	}

	masterEngine := dbEngines.MasterEngine()
	slaveEngine := dbEngines.SlaveEngine()

	log.Infof("dbMaster:%+v", dbMaster)
	log.Infof("dbSlave:%+v", dbSlave)
	log.Info("mysql conn url:", GetConnURL(&dbMaster))
	engineGroup, err = xorm.NewEngineGroup(masterEngine, []*xorm.Engine{slaveEngine})
	if err != nil {
		golog.Fatalf("配置数据库连接失败: %s", err)
	}
	engineGroup.SetMaxOpenConns(50)
	log.Info("xorm engine ", engineGroup.Ping())

}
